package com.wosai.teach.utils;

import java.util.List;

import android.content.Context;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.DbUtils.DaoConfig;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

public class DBControl {
	private static DBControl dbc;

	private static DbUtils db;

	/**
	 * 构造器
	 */
	private DBControl() {

	}

	public void init(Context context) {
		if (db == null) {
			DaoConfig config = new DaoConfig(context);
			config.setDbName("teach.db"); // db名
			config.setDbVersion(9); // db版本
			db = DbUtils.create(config);
		}
	}

	/**
	 * 获取DBUtil的单例
	 */
	public static DBControl getInstance() {
		if (dbc == null) {
			dbc = new DBControl();
		}
		return dbc;
	}

	public static DbUtils getDb() {
		return db;
	}

	public <T> T findFirst(Selector selector) {
		T obj = null;
		try {
			obj = DBControl.getDb().findFirst(selector);
		} catch (DbException e) {
			e.printStackTrace();
		}
		return obj;
	}

	public <T> T findFirst(Class<T> entityType) {
		T obj = null;
		try {
			obj = DBControl.getDb().findFirst(entityType);
		} catch (DbException e) {
			e.printStackTrace();
		}
		return obj;
	}

	/**
	 * 查找id为1的数据
	 * 
	 * @param entityType
	 * @return
	 */
	public <T> T getFirst(Class<T> entityType) {
		T obj = null;
		try {
			obj = DBControl.getDb().findFirst(
					Selector.from(entityType).where("id", "=", "1"));
		} catch (DbException e) {
			e.printStackTrace();
		}
		return obj;
	}

	public void save(Object entity) {
		try {
			DBControl.getDb().save(entity);
		} catch (DbException e) {
			e.printStackTrace();
		}
	}

	public void saveAll(List<?> entities) {
		try {
			DBControl.getDb().saveAll(entities);
		} catch (DbException e) {
			e.printStackTrace();
		}
	}

	public void saveOrUpdate(Object entity) {
		try {
			DBControl.getDb().saveOrUpdate(entity);
		} catch (DbException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 按条件查询
	 * 
	 * @param selector
	 * @return
	 */
	public <T> List<T> findAll(Selector selector) {
		List<T> tList = null;
		try {
			tList = DBControl.getDb().findAll(selector);
		} catch (DbException e) {
			e.printStackTrace();
		}
		return tList;
	}

	/**
	 * 按条件删除
	 * 
	 * @param selector
	 */
	public void deleteAll(Selector selector) {
		List<?> tList = this.findAll(selector);
		if (!OtherUtils.CheckNull(tList)) {
			try {
				DBControl.getDb().deleteAll(tList);
			} catch (DbException e) {
				e.printStackTrace();
			}
		}
	}
}
